const ajax = userOptions => {
	return new Promise((resolve, reject) => {
		//  默认配置项
		const DEFAULT = {
			url: "",
			method: "GET",
			data: {},
			type: '',
			headers: {}
		};

		//  先与用户合并，再通过解构赋值，拿到需要的参数
		const { url, method, data, type, headers } = Object.assign({}, DEFAULT, userOptions);

		try {
			const xhr = new XMLHttpRequest();
			//  判断请求方式，决定发送数据的行为
			if (method.toUpperCase() === "GET") {
				let newUrl = url + '?';
				for (let k in data) {
					newUrl += `${k}=${data[k]}&`;
				};
				newUrl = newUrl.slice(0, -1);
				xhr.open("GET", newUrl, true);
				setHeaders(headers);
				xhr.send(null);
			} else {
				xhr.open(method, url, true);
				setHeaders(headers);
				//  判断发送格式是否为json
				if (type) {
					//  json
					xhr.setRequestHeader('Content-Type', 'application/json');
					xhr.send(JSON.stringify(data));
				} else {
					//  application/x-www-form-urlencoded
					xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					let postData = "";
					for (let k in data) {
						postData += `${k}=${data[k]}&`;
					};
					postData = postData.slice(0, -1);
					xhr.send(postData);

				}
			}

			xhr.addEventListener('readystatechange', () => {
				if (xhr.readyState === 4) {
					if (xhr.status === 200) {
						return resolve(JSON.parse(xhr.response));
					} else {
						return reject(JSON.parse(xhr.response));
					}
				}
			});

			// 请求头封装
			function setHeaders(headers) {
				for (let k in headers) {
					xhr.setRequestHeader(k, headers[k]);
				}
			}
		} catch (error) {
			reject(error);
		}
	})
};

export default ajax;